<template>
  <el-dialog title="选择备件" :visible.sync="dialogVisible" width="80%" :close-on-click-modal="false">
    <div class="part-selector">
    <!-- 搜索条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="备件编号" prop="partNo">
        <el-input
          v-model="queryParams.partNo"
          placeholder="请输入备件编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备件名称" prop="name">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入备件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备件类型" prop="partTypeCode">
        <el-select
          v-model="queryParams.partTypeCode"
          placeholder="请选择备件类型"
          clearable
        >
          <el-option label="全部" value="" />
          <el-option label="工具" value="TOOL" />
          <el-option label="零件" value="PART" />
          <el-option label="耗材" value="CONSUMABLE" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 状态说明 -->
    <div style="margin-bottom: 10px; padding: 8px 12px; background-color: #f0f9ff; border: 1px solid #b3d8ff; border-radius: 4px; font-size: 12px; color: #409eff;">
      <i class="el-icon-info"></i>
      <span style="margin-left: 4px;">
        状态说明：<span style="color: #67c23a;">可盘点</span> - 可以添加到盘点单；<span style="color: #e6a23c;">待盘点</span> - 已在其他盘点单中，不可重复选择
      </span>
    </div>

    <!-- 备件列表 -->
    <el-table
      v-loading="loading"
      :data="partList"
      @selection-change="handleSelectionChange"
      height="300"
    >
      <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" />
      <el-table-column label="备件编号" align="center" prop="partNo" width="120" />
      <el-table-column label="备件名称" align="center" prop="partName" width="150" />
      <el-table-column label="规格型号" align="center" prop="specNo" width="120" />
      <el-table-column label="备件类型" align="center" prop="partTypeCode" width="100">
        <template slot-scope="scope">
          <type-tag :value="scope.row.partTypeCode" type="partType" />
        </template>
      </el-table-column>
      <el-table-column label="库存数量" align="center" prop="stockTotal" width="100">
        <template slot-scope="scope">
          <span>{{ Math.floor(scope.row.stockTotal || 0) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isPending" type="warning" size="mini">待盘点</el-tag>
          <el-tag v-else type="success" size="mini">可盘点</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 操作按钮 -->
    <div slot="footer" class="dialog-footer" style="text-align: right; margin-top: 20px;">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </div>
    </div>
  </el-dialog>
</template>

<script>
import { listPart, listPartDTO } from '@/api/inventory/part'
import TypeTag from './TypeTag.vue'

export default {
  name: 'PartSelector',
  components: {
    TypeTag
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    warehouseCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      partList: [],
      total: 0,
      selectedParts: [],
      pendingPartNos: [], // 待盘点盘点单中的备件编号
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        partNo: null,
        partName: null,
        partTypeCode: null,
        warehouseCode: null
      }
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal
      },
      immediate: true
    },
    dialogVisible: {
      handler(newVal) {
        this.$emit('update:visible', newVal)
      }
    },
    warehouseCode: {
      handler(newVal) {
        this.queryParams.warehouseCode = newVal
        this.getList()
      },
      immediate: true
    }
  },
  created() {
    this.getList()
    this.loadPendingPartNos()
  },
  methods: {
    /** 查询备件列表 */
    getList() {
      this.loading = true
      const params = {
        ...this.queryParams
      }
      // 如果有仓库编码，添加到查询参数中
      if (this.warehouseCode) {
        params.warehouseCode = this.warehouseCode
      }
      
      listPartDTO(params).then(response => {
        // 处理返回的数据结构
        if (response.code === 200) {
          let allParts = response.data || []
          
          // 不再过滤待盘点的备件，而是标记状态
          if (this.pendingPartNos && this.pendingPartNos.length > 0) {
            allParts = allParts.map(part => ({
              ...part,
              isPending: this.pendingPartNos.includes(part.partNo)
            }))
          } else {
            allParts = allParts.map(part => ({
              ...part,
              isPending: false
            }))
          }
          
          this.partList = allParts
          this.total = allParts.length
        } else {
          this.partList = []
          this.total = 0
          this.$message.error(response.msg || '获取备件列表失败')
        }
        this.loading = false
      }).catch(error => {
        console.error('获取备件列表失败:', error)
        this.partList = []
        this.total = 0
        this.loading = false
        this.$message.error('获取备件列表失败')
      })
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        partNo: null,
        partName: null,
        partTypeCode: null,
        warehouseCode: this.warehouseCode
      }
      this.handleQuery()
    },
    
    /** 加载待盘点盘点单中的备件编号 */
    loadPendingPartNos() {
      // 使用现有的盘点列表API来获取待盘点的盘点单
      import('@/api/inventory/inventory').then(api => {
        // 获取所有盘点单，然后筛选出待盘点的
        api.listInventory({ pageNum: 1, pageSize: 9999 }).then(response => {
          if (response.rows && Array.isArray(response.rows)) {
            // 筛选出状态为'PENDING'的盘点单
            const pendingInventories = response.rows.filter(inv => inv.status === 'PENDING')
            
            if (pendingInventories.length === 0) {
              this.pendingPartNos = []
              return
            }
            
            // 获取每个待盘点盘点单的详细信息
            const pendingPartNos = []
            let completedRequests = 0
            
            pendingInventories.forEach(inventory => {
              api.getInventory(inventory.sessionNo).then(detailResponse => {
                if (detailResponse.data && detailResponse.data.partList && Array.isArray(detailResponse.data.partList)) {
                  detailResponse.data.partList.forEach(part => {
                    if (part.partNo && !pendingPartNos.includes(part.partNo)) {
                      pendingPartNos.push(part.partNo)
                    }
                  })
                }
                
                completedRequests++
                if (completedRequests === pendingInventories.length) {
                  // 所有请求完成，更新待盘点备件编号
                  this.pendingPartNos = [...pendingPartNos]
                  // 重新加载备件列表以过滤掉待盘点的备件
                  this.getList()
                }
              }).catch(error => {
                console.error('获取盘点单详情失败:', error)
                completedRequests++
                if (completedRequests === pendingInventories.length) {
                  this.pendingPartNos = [...pendingPartNos]
                }
              })
            })
          } else {
            this.pendingPartNos = []
          }
        }).catch(error => {
          console.error('获取盘点列表失败:', error)
          // 如果获取失败，设置为空数组，不影响正常选择
          this.pendingPartNos = []
        })
      }).catch(error => {
        console.error('导入API失败:', error)
        this.pendingPartNos = []
      })
    },
    
    
    /** 检查行是否可选择 */
    checkSelectable(row) {
      // 待盘点的备件不可选择
      return !row.isPending
    },
    
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.selectedParts = selection
    },
    
    
    /** 确认选择 */
    handleConfirm() {
      if (this.selectedParts.length === 0) {
        this.$message.warning('请选择至少一个备件')
        return
      }
      
      // 直接确认选择（待盘点的备件已经在UI层面被禁用）
      this.$emit('confirm', this.selectedParts)
      this.dialogVisible = false
    },
    
    
    /** 取消选择 */
    handleCancel() {
      this.selectedParts = []
      this.dialogVisible = false
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
.part-selector {
  padding: 20px;
}
</style>
